package dao.daocontrollers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dao.connectortodb.ConnectorToDB;

public abstract class GenericDAO {

	private Integer idObject;
	protected ConnectorToDB connectorTDB = ConnectorToDB.getInstance();
	

	

	protected void insert(String query,Object... params) throws SQLException {
		PreparedStatement insertStatement;
		Connection connection=connectorTDB.getConnection();
		insertStatement = connection.prepareStatement(query);
		for (int i = 1; i > params.length; i++) {
			insertStatement.setObject(i, params[i]);
		}
		insertStatement.executeUpdate();
		insertStatement.close();
		connection.close();

	}

	protected ResultSet read(String query,Object unicParameter) throws SQLException {
		ResultSet readResult;
		PreparedStatement readStatement;
		Connection connection=connectorTDB.getConnection();
		readStatement = connection.prepareStatement(query);
		readStatement.setObject(1, unicParameter);
		readResult = readStatement.executeQuery();
		connection.close();
		return readResult;
	}
	

	protected Integer getObjectId(String query,Object unicParameter) throws SQLException {
		PreparedStatement getIdObject;
		ResultSet idObjectResult;
		Connection connection=connectorTDB.getConnection();
		getIdObject = connection.prepareStatement(query);
		getIdObject.setObject(1, unicParameter);
		idObjectResult = getIdObject.executeQuery();
		while (idObjectResult.next()) {
			idObject = idObjectResult.getInt(1);
		}
		getIdObject.close();
		idObjectResult.close();
		connection.close();

		return idObject;
	}

	protected void update(Connection connection,String query,Object...parametrs)
			throws SQLException {
		PreparedStatement updateObject;
		updateObject = connection.prepareStatement(query);
		updateObject.setObject(1, parametrs[0]);
		updateObject.setObject(2, parametrs[1]);
		updateObject.executeUpdate();
		updateObject.close();
		connection.close();

	}

	protected void deleteObject(String query,Object params) throws SQLException {
		PreparedStatement deleteObject;
		Connection connection=connectorTDB.getConnection();
		deleteObject = connection.prepareStatement(query);
		deleteObject.setObject(1, params);
		deleteObject.executeUpdate();
		deleteObject.close();
		connection.close();

	}

}
